package com.tiantian.web.controller.info;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tiantian.bean.PageBean;
import com.tiantian.cache.user.UserInfo;
import com.tiantian.cache.user.UserInfoCache;
import com.tiantian.domain.Businessusers;
import com.tiantian.domain.Buyersusers;
import com.tiantian.domain.Sysinformation;
import com.tiantian.domain.Usermessages;
import com.tiantian.ret.Result;
import com.tiantian.service.BusinessUsersService;
import com.tiantian.service.BuyersUsersService;
import com.tiantian.service.InfoService;
import com.tiantian.service.UserMessagesService;
import com.tiantian.util.CommonConstant;
import com.tiantian.util.PageUtil;
import com.tiantian.web.datatables.DataTableReturn;

@Controller

@RequestMapping("/info")
public class InfoController {

	@Resource
	private InfoService infoService;

	@Resource
	private UserMessagesService userMessageService;
	
	@Resource
	private BusinessUsersService businessUserService;
	
	@Resource
	private BuyersUsersService buyerUserService;
	
	public static final Logger LOG = LoggerFactory
			.getLogger(InfoController.class);

	/**
	 * 前往消息中心
	 * 
	 * @return
	 */
	@RequestMapping("/infoList")
	public String infoList() {
		return "info/infoList";
	}

	/**
	 * 获取消息中心信息
	 * 
	 * @param vo
	 * @param request
	 * @return
	 */
	@RequestMapping("/getInfoList")
	@ResponseBody
	public Object getInfoList(InfoVo vo, HttpServletRequest request) {
		PageBean page = PageUtil.parseRequest2PageBean(request);
		Map<String, String> params = null;
		try {
			params = BeanUtils.describe(vo);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			params = new HashMap<String, String>();
		}
		List<Map<String, Object>> data = infoService.list(params,
				page);
		return new DataTableReturn(page.getDraw(), page.getTotal(),
				page.getTotal(), data);
	}
	/**
	 * 消息详情
	 * @param infoId
	 * @param map
	 * @return
	 */
	@RequestMapping("/details")
	public String details(String infoId,ModelMap
			map) {
		map.put("info", this.infoService.getInfoByIfoId(infoId));
		return "info/details";
	}
	
	
	/**
	 * 前往消息新增界面
	 * @param id
	 * @param map
	 * @return
	 */
	@RequestMapping("/toAdd")
	public String toAdd(String id,ModelMap
			map) {
		Map<String,Object> info=new HashMap<>();
		info.put("sendtime",DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss") );
		
		map.put("info", info);
		return "info/add";
	}
	
	/**
	 * 新增消息
	 * @param info
	 * @param request
	 * @return
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Object add(Sysinformation info,String ids, HttpServletRequest request) {
		try {
			UserInfo user=UserInfoCache.getCurrentUser();
			info.setAnnouncer(user.getUserId());
			String sendTime=DateFormatUtils.format(new Date(), "yyyy-MM-dd");
			String id=this.infoService.getInfoId(sendTime);
			sendTime=sendTime.replace("-", "");
			if(id==null){
				info.setSysinfoNo(1);
				info.setSysinfoId(sendTime+"001");
			}else{
				int no=Integer.parseInt(id.substring(8,id.length()));
				no++;
				info.setSysinfoNo(no);
				if(no<10){
					info.setSysinfoId(sendTime+"00"+no);
				}else if(no<100){
					info.setSysinfoId(sendTime+"0"+no);
				}else if(no<1000){
					info.setSysinfoId(sendTime+no);
				}
				
			}
			this.infoService.save(info);
			
			
			

			String no=this.userMessageService.getMsgNo(sendTime);
			if(no==null){
				no="1";
			}
			int msgNo=Integer.parseInt(no);
			List<String> userIds=new ArrayList<>();	
			List<Character> userType=new ArrayList<>();	
			if('0'==info.getScope()){
				//全部
				Iterable<Businessusers> business=this.businessUserService.findAll();
				Iterator<Businessusers> iterBusiness=business.iterator();
				while(iterBusiness.hasNext()){
					Businessusers b=iterBusiness.next();
					userIds.add(b.getBusinessUserId());
					userType.add('2');
				}
				
				Iterable<Buyersusers> buyer=this.buyerUserService.findAll();
				Iterator<Buyersusers> iterBuyer=buyer.iterator();
				while(iterBuyer.hasNext()){
					Buyersusers b=iterBuyer.next();
					userIds.add(b.getBuyersUserId());
					userType.add('1');
				}
				
				
			}else if('1'==info.getScope()){
				//商家
				Iterable<Businessusers> business=this.businessUserService.findAll();
				Iterator<Businessusers> iterBusiness=business.iterator();
				while(iterBusiness.hasNext()){
					Businessusers b=iterBusiness.next();
					userIds.add(b.getBusinessUserId());
					userType.add('2');
				}
			}else if('2'==info.getScope()){
				//买手
				Iterable<Buyersusers> buyer=this.buyerUserService.findAll();
				Iterator<Buyersusers> iterBuyer=buyer.iterator();
				while(iterBuyer.hasNext()){
					Buyersusers b=iterBuyer.next();
					userIds.add(b.getBuyersUserId());
					userType.add('1');
				}
			}else if('3'==info.getScope()){
				String[] str=StringUtils.split(ids,",");
				for(String s:str){
					Businessusers business=this.businessUserService.get(s);
					if(business!=null){
						userIds.add(business.getBusinessUserId());
						userType.add('2');
					}else{
						Buyersusers buyer=this.buyerUserService.get(s);
						if(buyer!=null){
							userIds.add(buyer.getBuyersUserId());
							userType.add('1');
						}
					}
				}
			}
			int i=0;
			List<Usermessages> list=new ArrayList<>();
			for(String s:userIds){
				Usermessages message=new Usermessages();
				Date time=new Date(System.currentTimeMillis());
				message.setMsgNo(msgNo++);
				message.setUserId(s);
				message.setMessageId(sendTime+message.getMsgNo());
				message.setMessageContent(info.getSendContent());
				message.setSendTime(time);
				message.setMsgType(CommonConstant.MESSAGE_TYPE.info.getId());
				message.setMsgTitle("系统消息");
				message.setUserType(userType.get(i++));	
				message.setPublisherType('0');
				message.setPublisher(UserInfoCache.getCurrentUser().getUserId());
				message.setMsgStatus('0');//未读
				message.setAssociationId(info.getSysinfoId());
				list.add(message);
			}
			this.userMessageService.save(list);
		
			
			
			
			
			
			return new Result<Object>(true, "新增消息成功");
		} catch (Exception e) {
			LOG.error("新增消息异常：",e);
			return new Result<Object>(false, "新增消息失败");
		}
	}
}

